/***********************************************************************
 *
 * Copyright (C) 2009 Graeme Gott <graeme@gottcode.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

#include "window.h"
/*#include <QApplication>
#include <QDialog>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QMenu>
#include <QSoftMenuBar>
#include <QMenuBar>
#include <QMessageBox>
#include <QSettings>
#include <QSpinBox>
#include <QUndoStack>
#include <QVBoxLayout>
#include <QKeyEvent>*/
#include <QRegExp>
#include <QDebug>
#include <QFile>

/*****************************************************************************/

Window::Window( QWidget *parent = 0, Qt::WFlags f = 0 ) : QMainWindow(parent, f)
{
    setupUi(this);
/*    lst->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    lst->setWrapping(false);
    lst->setWordWrap(true);*/
    m_Http = new QHttp(this);
    connect( m_Http, SIGNAL(done(bool)), SLOT(requestDone(bool)));
    sendRequest("http://www.3dnews.ru/news/rss/");
}

bool Window::parseRSSFood(QString data, rsscontent* out)
{
    int i = 0, pos;
    QRegExp rx;
    rx.setMinimal(true);
    rx.setPattern("\"title\":\"(.*)\",\"link\":\"(.*)\",\"author\":\"(.*)\",\"description\":\"(.*)\",\"type\":\"(.*)\",\"entries\":\\[");
    if((pos = rx.indexIn(data, 0)) != -1)
    {
        out->feed_title = rx.cap(1);
        out->feed_link = rx.cap(2);
        out->feed_author = rx.cap(3);
        out->feed_desc = rx.cap(4);
        out->feed_type = rx.cap(5);
        pos += rx.matchedLength();

        rx.setPattern("\"title\":\"(.*)\",\"link\":\"(.*)\",\"author\":\"(.*)\",\"publishedDate\":\"(.*)\",\"contentSnippet\":\"(.*)\",\"content\":\"(.*)\",\"categories\":\\[(.*)\\]");
        while((pos = rx.indexIn(data, pos)) != -1) {
            out->title << rx.cap(1);
            out->link << rx.cap(2);
            out->author << rx.cap(3);
            out->date << rx.cap(4);
            out->snippet << rx.cap(5);
            out->text << rx.cap(6);
            out->categories << rx.cap(7);
            pos += rx.matchedLength();
            i++;
        }
        out->count = i;
        return true;
    }
    else return false;
}


void Window::sendRequest(QString feedUrl)
{
    m_Http->abort();
    feedUrl = QString::fromUtf8(QUrl::toPercentEncoding(feedUrl));
    QString url = QString("/ajax/services/feed/load?q=" + feedUrl + "&v=1.0");
    QHttpRequestHeader header = QHttpRequestHeader("GET", url);
    header.setValue("Host", "ajax.googleapis.com");
    m_Http->setHost("ajax.googleapis.com");
    m_Http->request(header);

//    setBlocking( true );
}

void Window::requestDone(bool error)
{
//    setBlocking( false );
    if( error == false ) printRSS(QString::fromUtf8(m_Http->readAll()));
    else qDebug("HTTP request error.");
}

void Window::printRSS(QString str)
{
    QListWidgetItem* item;
    QFont font;
    font.setPointSize(4);

    rsscontent rss;
    if(parseRSSFood(str, &rss))
    {
        qDebug() << "Feed Title: " << rss.feed_title
             << "\nFeed Link: " << rss.feed_link
             << "\nFeed Author: " << rss.feed_author
             << "\nFeed Description: " << rss.feed_desc
             << "\nFeed Type: " << rss.feed_type
             << "\n";
        for(int i = 0; i < rss.count; i++) {
            qDebug()<<"Title: "<<rss.title[i]
                 <<"\nLink: "<<rss.link[i]
                 <<"\nAuthor: "<<rss.author[i]
                 <<"\nDate: "<<rss.date[i]
                 <<"\nSnippet: "<<rss.snippet[i]
                 <<"\nText: "<<rss.text[i]
                 <<"\nCategories: "<<rss.categories[i]
                 <<"\n";
                lst->addItem(rss.title[i]);
                item = new QListWidgetItem(rss.snippet[i]);
                item->setFont(font);

                lst->addItem(item);
        }
    }
    else qDebug("Data cannot be parsed.");
}

/*****************************************************************************/

/*void Window::closeEvent(QCloseEvent* event) {
        QSettings().setValue("Geometry", saveGeometry());
        QMainWindow::closeEvent(event);
}

void Window::keyPressEvent(QKeyEvent* event) {
    if(event->key() == Qt::Key_Select) newGame();
    else event->ignore();
}*/

/*****************************************************************************/

/*void Window::about() {
        QMessageBox::about(this, tr("About Peg-E"), tr("<center><big><b>Peg-E 1.0.0</b></big><br/>Peg elimination game<br/><small>Copyright &copy; 2009 Graeme Gott</small></center>"));
}*/

/*****************************************************************************/
